package com.txhy.certificatechain.ui.fragment.bottomnavigation;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ninetripods.aopermission.permissionlib.annotation.NeedPermission;
import com.txhy.certificatechain.R;
import com.txhy.certificatechain.api.UrlAddress;
import com.txhy.certificatechain.model.bean.UserBean;
import com.txhy.certificatechain.presenter.user.UserPresenter;
import com.txhy.certificatechain.ui.activity.base.BaseFragment;
import com.txhy.certificatechain.ui.manager.ImageLoaderManager;
import com.txhy.certificatechain.ui.view.user.UserView;
import com.txhy.certificatechain.ui.widget.RoundImageView;
import com.txhy.certificatechain.utils.BitmapUtil;
import com.txhy.certificatechain.utils.PrefUtil;
import com.txhy.certificatechain.utils.ToastUtil;

import butterknife.BindView;

/*
 * -----------------------------------------------------------------
 * Copyright (C) 2018-2030, by your company, All rights reserved.
 * -----------------------------------------------------------------
 * 文    件: UserFragment.java
 * 作    者: 侯建军
 * 版    权: 1.0.0
 * 描    述: 我的--底部导航
 * 创建时间: 2018/9/19 16:53
 * 更新时间：2018/9/19 16:53
 * -----------------------------------------------------------------
 * 2018/9/19 16:53: 创建 UserFragment.java (侯建军);
 * -----------------------------------------------------------------
 */
public class UserFragment extends BaseFragment<UserView, UserPresenter> implements UserView {
    @BindView(R.id.iv_photo)
    RoundImageView iv_photo;

    @BindView(R.id.ll_login)
    LinearLayout ll_login;

    @BindView(R.id.tv_name)
    TextView tv_name;

    @BindView(R.id.tv_time)
    TextView tv_time;

    @BindView(R.id.ll_goLogin)
    LinearLayout ll_goLogin;


    @BindView(R.id.ll_kaiTong)
    LinearLayout ll_kaiTong;

    @BindView(R.id.ll_myJyb)
    LinearLayout ll_myJyb;
    @BindView(R.id.ll_qiyeguan)
    LinearLayout ll_qiyeguan;

    private UserBean.DataEntity.MapEntity user;
    private UserBean userBean;

    @BindView(R.id.tv_kaitongjyb)
    TextView tv_kaitongjyb;
    @BindView(R.id.tv_wodejyb)
    TextView tv_wodejyb;

    public static UserFragment newInstance() {
        return new UserFragment();
    }

    @Override
    protected UserPresenter createPresenter() {
        return new UserPresenter();
    }


    @Override
    protected int provideContentViewId() {
        return R.layout.frag_user;
    }

    @Override
    public void initView(View rootView) {
        super.initView(rootView);
        setLoginUser();
    }

//    @OnClick({R.id.ll_kaiTong, R.id.ll_qiyeguan, R.id.ll_yaoQing, R.id.ll_myJyb, R.id.rl_imag, R.id.ll_service, R.id.ll_biologSetting, R.id.ll_mybankCard, R.id.ll_safety, R.id.yiJian, R.id.ll_setting})
//    public void onViewClicked(View view) {
//        switch (view.getId()) {
//            case R.id.ll_kaiTong://开通交易币账户
//                Intent intent2 = new Intent(getActivity(), WebViewActivity.class);
//                intent2.putExtra(WEB_URL, UrlAddress.JYBOPEN_URL);
//                intent2.putExtra("type", 0);
//                startActivity(intent2);
//                break;
//            case R.id.ll_yaoQing://邀请
//                startActivity(new Intent(getActivity(), ShareActivity.class));
//                break;
//            case R.id.ll_myJyb://
//                startActivity(new Intent(getActivity(), MyJybActivity.class));
//                break;
//            case R.id.ll_service://
//                if (!PrefUtil.getLoginBoolean(getActivity())) {
//                    CommUtils.doToLoad(getActivity());
//                    return;
//                }
//                startActivity(new Intent(getActivity(), ServiceCenterActivity.class));
//                break;
//            case R.id.ll_biologSetting://
//                startActivity(new Intent(getActivity(), BiologicalscenedActivity.class));
//                break;
//            case R.id.ll_mybankCard://
//                startActivity(new Intent(getActivity(), MyBankCardActivity.class));
//                break;
//            case R.id.ll_safety://
//                startActivity(new Intent(getActivity(), SafetyCenterActivity.class));
//                break;
//            case R.id.yiJian://
//                startActivity(new Intent(getActivity(), MyHelpActivity.class));
//                break;
//            case R.id.ll_setting://
//                startActivity(new Intent(getActivity(), SettingActivity.class));
//                break;
//            case R.id.rl_imag:
//                if (!PrefUtil.getLoginBoolean(getActivity())) {
//                    CommUtils.doToLoad(getActivity());
//                    return;
//                }
//                changeHeadImag();
//                break;
//            case R.id.ll_qiyeguan:
//                startActivity(new Intent(getActivity(), BusinessActivity.class));
//                break;
//        }
//    }

    @NeedPermission(value = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, requestCode = 0)
    private void changeHeadImag() {
        showHeadDialog(getActivity());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 2) {
            Uri uri = data.getData();
            mPresenter.upLoadImg(BitmapUtil.compressImage(getRealPathFromURI(uri)));
        }
        if (requestCode == 1) {//拍照
            if (resultCode == Activity.RESULT_OK) {
                mPresenter.upLoadImg(getRealPathFromURI(imgUri));
            }
        }
    }


    private String getRealPathFromURI(Uri contentURI) {
        String result;
        Cursor cursor = null;
        try {
            cursor = getActivity().getContentResolver().query(contentURI, null, null, null, null);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        if (cursor == null) {
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }

    private Dialog mHeadDialog;
    private Uri imgUri;

    //更换头像
    public Dialog showHeadDialog(Context context) {
        hideHeadDialog();
        mHeadDialog = new Dialog(context, R.style.MyDialog);
        LinearLayout root = (LinearLayout) LayoutInflater.from(context).inflate(
                R.layout.dialog_head, null);

        root.findViewById(R.id.tv_camera).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //启动相机程序
                imgUri = createImageUri(getActivity());
                Intent intent = new Intent();
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);//如果不设置EXTRA_OUTPUT getData()  获取的是bitmap数据  是压缩后的
                startActivityForResult(intent, 1);
                hideHeadDialog();
            }
        });
        root.findViewById(R.id.tv_photo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, 2);
                hideHeadDialog();
            }
        });
        root.findViewById(R.id.tv_cancle).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideHeadDialog();
            }
        });

        mHeadDialog.setContentView(root);
        Window dialogWindow = mHeadDialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        mHeadDialog.setCancelable(true);
        dialogWindow.setWindowAnimations(R.style.dialogstyle); // 添加动画
        WindowManager.LayoutParams lp = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        lp.x = 0; // 新位置X坐标
        lp.y = -20; // 新位置Y坐标
        lp.width = ((int) context.getResources().getDisplayMetrics().widthPixels); // 宽度
        root.measure(0, 0);
        lp.height = root.getMeasuredHeight();
        lp.alpha = 9f; // 透明度
        dialogWindow.setAttributes(lp);
        mHeadDialog.show();
        return mHeadDialog;
    }

    /**
     *
     */
    public void hideHeadDialog() {
        if (mHeadDialog != null) {
            mHeadDialog.dismiss();
            mHeadDialog = null;
        }
    }

    /**
     *
     * @param context
     * @return
     */
    private static Uri createImageUri(Context context) {
        String name = "takePhoto" + System.currentTimeMillis();
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Images.Media.TITLE, name);
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, name + ".jpeg");
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        return uri;
    }

    /**
     *
     * @param msg
     */
    @Override
    public void upMsgSuccess(String msg) {
        mPresenter.upDataImg(user.getId() + "", msg, user.getUserType());

    }

    /**
     *
     * @param msg
     */
    @Override
    public void upMsgFail(String msg) {
        ToastUtil.showLong(getActivity(), msg);
    }

    @Override
    public void upDataImgSuccess(String msg) {
        ImageLoaderManager.LoadImage(getActivity(), UrlAddress.IMGBASE_URL + msg, iv_photo);
        userBean.getData().getMap().get(PrefUtil.getShengType(getActivity())).setLogo(msg);
        PrefUtil.setUserString(getActivity(), new Gson().toJson(userBean));
    }

    @Override
    public void upDataImgFail(String msg) {
        ToastUtil.showLong(getActivity(), msg);
    }


    public void setLoginUser() {
//        if (!PrefUtil.getLoginBoolean(getActivity())) {
//            ll_login.setVisibility(View.GONE);
//            tv_name.setText("请登录");
//            ll_goLogin.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    CommUtils.doToLoad(getActivity());
//                }
//            });
//        } else {
//            userBean = PrefUtil.getUserString(getActivity());
//            user = PrefUtil.getUserBean(getActivity());
//            if (TextUtils.isEmpty(user.getLogo())) {
//                iv_photo.setImageResource(R.mipmap.defheardimg);
//            } else {
//                ImageLoaderManager.LoadImage(getActivity(), UrlAddress.IMGBASE_URL + user.getLogo(), iv_photo);
//            }
//
//            tv_name.setText(user.getEnterpriseName());
//            Date date = new Date(System.currentTimeMillis());
//            Long endTime = date.getTime();
//            Long startTime = userBean.getData().getCareteTime();
//            tv_time.setText("这是您使用证有币要的第" + CommUtils.formatTime(endTime - startTime) + "天");
//
//            ll_login.setVisibility(View.VISIBLE);
//            if (!TextUtils.isEmpty(user.getAccountNo())) {
//                ll_myJyb.setVisibility(View.VISIBLE);
//                ll_kaiTong.setVisibility(View.GONE);
//            } else {
//                ll_myJyb.setVisibility(View.GONE);
//                ll_kaiTong.setVisibility(View.VISIBLE);
//            }
//
//            switch (user.getUserType()) {
//                case "0"://人
//                    ll_qiyeguan.setVisibility(View.GONE);
//                    tv_kaitongjyb.setText(UIUtils.getString(R.string.kaitongjiaoyi));
//                    tv_wodejyb.setText(UIUtils.getString(R.string.wodejiaoyibi));
//
//                    break;
//                case "1"://qiye
//                    ll_qiyeguan.setVisibility(View.VISIBLE);
//                    tv_kaitongjyb.setText("开通企业交易币账户");
//                    tv_wodejyb.setText("企业交易币账户");
//                    break;
//            }
//        }
    }
}

